
$(function(){

    let editId=null
init()
    function init (){
        $.ajax({
            url:'http://localhost:8080/api/v1/admin/category/list',
            headers:{
                Authorization:localStorage.getItem('token')
            },
            success:function(res){
                // console.log(res)
                if(res.code===200){
               $('.category_table tbody').html(template('tirps',res))
                }
            }
        })
    }
    


$('#myModal .btn_opt').on('click',function(){
    let name=$("[name='name']").val().trim()
    let slug=$("[name='slug']").val().trim()
    // console.log(name,slug)

    $.ajax({
        url:'http://localhost:8080/api/v1/admin/category/add',
        type:'post',
        headers:{
            Authorization:localStorage.getItem('token')
        },
        data:{name,slug},
        success:function(res){
            // console.log(res)
            if(res.code===200){
                $("[name='name']").val('')
                $("[name='slug']").val('')
                $('#myModal').modal('hide')
                init()
            }
        }
    })
})

$('.table-bordered').on('click','.edit',function(){
    $('#editModal').modal('show')
   let value= $(this).parents('tr').data('value')
    $("[id='name']").val(value.name)
    $("[id='slug']").val(value.slug)
   editId=value.id
      console.log(editId)
  
})
//编辑模态框,保存按钮事件
$('#editModal .btn_opt').on('click',function(){
    //获取分类名和别名
let slug=$("[id='slug']").val().trim()
let name=$("[id='name']").val().trim()

//发起请求
$.ajax({
 url:'http://localhost:8080/api/v1/admin/category/edit',
 type:'post',
 headers:{
    Authorization:localStorage.getItem('token')
},
 data:{id:editId,name,slug},
 success(res){
    if(res.code===200){
        console.log(res)
        //刷新数据
        init()
        //隐藏模态框
        $('#editModal').modal('hide')
    }else{
        console.log('失败')
        console.log(res)

    }
 }
})
})
//删除按钮事件
$('.table-bordered').on('click',' .delete',function(){

layer.confirm('确定要删除吗?', (index)=>{
    let id= $(this).parents('tr').data('value').id
    // console.log(id)
    $.ajax({
        url:'http://localhost:8080/api/v1/admin/category/delete',
        headers:{
            Authorization:localStorage.getItem('token')
        },
        type:'post',
        data:{id},
        success(res){
            if(res.code===200){
                 init()
                layer.close(index);
            }else{
                console.log('失败')
                console.log(res)
            }
            
        }

    })
  });
})
})
